package phone.qyg.com.qyg.activity;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.app.adapter.recycler.CommonAdapter;
import com.app.adapter.recycler.MultiItemTypeAdapter;
import com.app.adapter.recycler.RecyclerViewItemDecoration;
import com.app.adapter.recycler.base.ViewHolder;
import com.app.application.QXApplication;
import com.app.base.tool.BaseActivity;
import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.JSONTool;
import com.app.utils.OptionImageUtils;
import com.app.utils.PromptManager;
import com.app.utils.SharePrefUtil;
import com.app.utils.TransformController;
import com.app.view.BaseViewStateLayout;
import com.app.xutils.MyCallBack;
import com.app.xutils.Xutils;
import com.liaoinstan.springview.container.AliFooter;
import com.liaoinstan.springview.container.AliHeader;
import com.liaoinstan.springview.widget.SpringView;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.MessageFormat;
import java.util.List;

import phone.qyg.com.qyg.R;
import phone.qyg.com.qyg.model.Base;
import phone.qyg.com.qyg.model.Content;
import phone.qyg.com.qyg.utils.AppHttpRequest;

/**
 * 作者：lblbh on 2017/12/11 11:19
 * 邮箱：lanbuhan@163.com
   功能：新闻列表
 */
@ContentView(R.layout.content_list)
public class ContentListActivity extends BaseActivity {

    @ViewInject(R.id.back)
    TextView back;

    @ViewInject(R.id.head_recycler)
    RecyclerView head_recycler;

    @ViewInject(R.id.linear)
    LinearLayout linear;

    BaseViewStateLayout baseView;

    CommonAdapter adapter;

    SpringView springview;

    RecyclerView recycler;

    List<Base> bases;//筛分条件集合

    List<Content> models;//新闻集合

    Base base;

    boolean isForce;

    int page_no,totalpage;


    @Override
    public void initData(Bundle savedInstanceState) {
       String appInfo = SharePrefUtil.getString(SharePrefUtil.KEY.APP_INFO,"");

       if(isRequestStr(appInfo)){
           setTypes(appInfo);
       }else{
           AppHttpRequest.httpAppInfo(new AppHttpRequest.OnAppHttpListener() {
               @Override
               public void onAppHttpState(boolean isState, String result) {
                   if(isState){
                       setTypes(result);
                   }
               }
           });
       }


        baseView = new BaseViewStateLayout(QXApplication.getContext()) {

            @Override
            public View obtionView() {
                View sucessView = View.inflate(QXApplication.getContext(), R.layout.base_spring_recycler,null);
                recycler = (RecyclerView) sucessView.findViewById(R.id.recycler);
                springview = (SpringView) sucessView.findViewById(R.id.springview);

                springview.setListener(new SpringView.OnFreshListener() {
                    @Override
                    public void onRefresh() {
                        isForce = true;
                        getInitNetwork(false);
                    }

                    @Override
                    public void onLoadmore() {
                        if(isRequestList(models) && (page_no < totalpage) ){
                            getInitNetwork(true);
                        }else{
                            PromptManager.showToast(R.string.more_no_datas);
                            springview.onFinishFreshAndLoad();
                        }

                    }
                });

                springview.setHeader(new AliHeader(QXApplication.getContext(),false));
                springview.setFooter(new AliFooter(QXApplication.getContext(),false));
                return sucessView;
            }

            @Override
            public Object obtionData() {
                return DELFAUTSTATE;
            }
        };

        ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        linear.addView(baseView,layoutParams);
        x.view().inject(linear);

    }




    private void setTypes(String result){

        if(isRequestStr(result)){
           bases = JSONTool.jsonDefaluTranClazzs(result, JSONTool.Enum.CULTURE_NEWS_TYPE, Base.class);

           if(isRequestList(bases)){
               base = bases.get(0);
               base.hintType = 1;
               setTypesData();
               getInitNetwork(false);
           }
        }

    }

    private void setTypesData() {
        if(!isRequestList(bases))return;
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        head_recycler.setLayoutManager(layoutVerManager);
        final CommonAdapter adapter = new CommonAdapter<Base>(QXApplication.getContext(),R.layout.item_app_type_two,bases){

            @Override
            protected void convert(ViewHolder holder, Base base, int position) {
                   holder.setText(R.id.one_key,base.title);
                   holder.setVisible(R.id.one_hint,(base.hintType==1)?true:false);
            }
        };

        adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Base tempBase = (Base) adapter.getData().get(position);
                if(tempBase == base)
                    return;
                isForce = true;
                tempBase.hintType = 1;
                base.hintType = 0;

                base = tempBase;
                isForce = true;
                getInitNetwork(false);

                adapter.notifyDataSetChanged();
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        head_recycler.setAdapter(adapter);
    }

    /**       
     * 执行网络请求
     */
    private void getInitNetwork(final boolean isPull){

        if(isPull){
            page_no = page_no + 1;
        }else{
            page_no = 1;
        }

        if(isForce){
            page_no = 1;
        }


        mapKeys.put(AppHttpKey.CLASSID,String.valueOf(base.id));
        mapKeys.put(AppHttpKey.PAGE_NO,String.valueOf(page_no));

        Xutils.Get(ApplicationConfig.NET_DSN_PATH + ApplicationConfig.CONTENT_LIST,
                mapKeys,
                new MyCallBack<String>(){
                    @Override
                    public void onSuccess(String result) {
                        super.onSuccess(result);

                        List<Content> temps = JSONTool.jsonDefaluTranClazzs(result,JSONTool.Enum.CONTENT_LIST, Content.class);

                        totalpage = JSONTool.requestJSONfindNameCount(result,JSONTool.Enum.DATA,JSONTool.Enum.TOTALPAGE);

                        if(!isRequestList(temps) && !isPull){
                            baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_EMPTY);
                            baseView.stateView();
                            return;
                        }
                        //成功获取到数据
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_SUCESS);
                        baseView.stateView();

                        setModelData(isPull,temps);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        super.onError(ex, isOnCallback);
                        baseView.setThreadOrState(BaseViewStateLayout.BaseViewState.STATE_ERROE);
                        baseView.stateView();
                    }

                    @Override
                    public void onFinished() {
                        super.onFinished();
                        springview.onFinishFreshAndLoad();
                    }
                });
    }

    private void setModelData(final boolean isPull, List<Content> temps) {
        if ((adapter == null && isRequestList(temps)) || isForce) {
            isForce = false;

            //数据初始化工作
            models = temps;

            final CommonAdapter adapter = new CommonAdapter<Content>(QXApplication.getContext(),R.layout.item_content,models) {
                @Override
                protected void convert(ViewHolder holder, Content model, int position) {
                    holder.setText(R.id.item_title,model.title);
                    holder.setText(R.id.item_address,model.dateDiff);
                    String source = MessageFormat.format(QXApplication.getContext().getResources().getString(R.string.source_key),
                            CommonUtil.setAttributeText(model.source));
                    holder.setText(R.id.item_source,source);
                    holder.setImageState(R.id.item_img,model.fixImgUrl, OptionImageUtils.getRectRatio43());
                }
            };

            adapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                    Object obj = adapter.getDatas().get(position);
                    TransformController.transformControllerModel(QXApplication.getContext(), HtmlActivity.class,obj);
                }

                @Override
                public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                    return false;
                }
            });


            recycler.setAdapter(adapter);

        }

        if (isPull && isRequestList(models) && isRequestList(temps)) {
            //上拉加载数据
            models.addAll(temps);
        }

//        //刷新数据
        if (adapter != null)
            adapter.notifyDataSetChanged();
    }

    @Event(value = {R.id.back})
    private void viewOnClick(View v){
        switch (v.getId()){
            case R.id.back:
                this.finish();
                break;
        }
    }

    @Override
    public void initSucessView() {}

    @Override
    public void initViewHandler() {
        if(recycler == null)return;
        LinearLayoutManager layoutVerManager = new LinearLayoutManager(QXApplication.getContext());
        layoutVerManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycler.addItemDecoration(new RecyclerViewItemDecoration(
                RecyclerViewItemDecoration.MODE_HORIZONTAL,
                getResources().getColor(R.color.divider),
                CommonUtil.dip2px(QXApplication.getContext(),1),0,0));
        recycler.setLayoutManager(layoutVerManager);
    }

}
